package com.cy.pj.sys.service.aspect;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.service.SysLogService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {
    private static final Logger log= LoggerFactory.getLogger(SysLogAspect.class);

    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredLog)")
    public void doLog(){}

    //@Around("@annotation(com.cy.pj.common.annotation.RequiredLog)")
    @Around("doLog()")
    public Object   doAround(ProceedingJoinPoint jp) throws Throwable {
        long t1=System.currentTimeMillis();
        log.info("Start:{}",t1);
        try {
            Object result = jp.proceed();//调用目标方法
            long t2=System.currentTimeMillis();
            log.info("opertime:{}",t2-t1);
            doLogInfo(jp, t2-t1, null);
            return result;
        } catch (Throwable e) {
            e.printStackTrace();
            long t2=System.currentTimeMillis();
            log.info("After:{}",t2);
            doLogInfo(jp, t2-t1, e);
            log.info("exception:{}",e.getMessage());
            throw e;
        }
    }

    @Autowired
    private SysLogService sysLogService;
    private void doLogInfo(ProceedingJoinPoint jp,Long time,Throwable e) throws Exception{
        String username="cgb";
        String ip="202.106.0.20";
        Class<?> targetCls = jp.getTarget().getClass();

        MethodSignature ms= (MethodSignature) jp.getSignature();
        Method targetMethod = targetCls.getMethod(ms.getName(), ms.getParameterTypes());
        RequiredLog annotation = targetMethod.getAnnotation(RequiredLog.class);
        String operation = annotation.operation();

        String classMethodName=targetCls.getName()+"."+targetMethod.getName();
//        System.out.println("--------------------------------"+classMethodName);

        Object[] args = jp.getArgs();//实际参数
        String params=new ObjectMapper().writeValueAsString(args);

        SysLog sysLog=new SysLog();
        sysLog.setUsername(username);
        sysLog.setIp(ip);
        sysLog.setOperation(operation);
        sysLog.setMethod(classMethodName);
        sysLog.setParams(params);
        sysLog.setTime(time);
        if(e!=null){
            sysLog.setStatus(0);
            sysLog.setError(e.getMessage());
        }

//        new Thread(){
//            @Override
//            public void run() {
//                sysLogService.insertLog(sysLog);
//            }
//        }.start();
    }
}
